<?php
namespace app\admin\controller;
use app\admin\model\IndexTableModel;
use app\admin\model\JoinTableModel;
use think\Db;
use think\Request;
use app\common\model\User;
use app\common\model\UserLevel;
use app\common\validate\UserValidate;

require_once (__DIR__.'/../../../vendor/ReidsLock.class.php');
class FadaytimeController extends Controller
{

    /**
     * 时间段统计
     * User:@hang
     */
    public function index(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['json_time']) && !empty($param['json_time'])) {
            $whehe[] = ['json_time','=',$param['json_time']];
        }
        $IndexTableModel = New IndexTableModel();
        $data = Db::table('fa_time_list_info')
            ->where($whehe)
            ->field('*')
            ->order("id desc")
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);

        $data->each(function ($v, $k)use($IndexTableModel) {
            $v['json_arr'] = json_decode($v['json_info'],true);
            return $v;
        });
        $time_arr = ['0-1','1-2','2-3','3-4','4-5','5-6','6-7','7-8','8-9','9-10','10-11','11-12','12-13','13-14','14-15','15-16','16-17','17-18','18-19','19-20','20-21','21-22','22-23','23-24'];
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
            'time_arr' => $time_arr,
        ]);
        return $this->fetch();
    }


    /**
     * 每日聊天次数排名
     * User:@hang
     */
    public function getmsgnums(Request $request)
    {
        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['f.member_id','=',$param['member_id']];
        }
//        $param['day_time'] = '2024-12-24';//测试
        if (isset($param['day_time']) && !empty($param['day_time'])) {
            $start_time = strtotime($param['day_time'].' 00:00:00');//开始秒
            $end_time = strtotime($param['day_time'].' 23:59:59');//结束秒
            $start_time_hm = bcmul($start_time,1000,0);//开始毫秒
            $end_time_hm = bcmul($end_time,1000,0);//结束毫秒
        }else{
            $start_time = strtotime("yesterday");//开始秒
            $end_time = $start_time + 86399;//结束秒
            $start_time_hm = bcmul($start_time,1000,0);//开始毫秒
            $end_time_hm = bcmul($end_time,1000,0);//结束毫秒
            $param['day_time'] = date('Y-m-d',$start_time);
        }

//        $data = Db::table('fa_rong_msg')
//            ->alias('a')
//            ->join('fa_member f', 'a.fromUserId = f.member_id')
//            ->join('fa_member s', 'a.toUserId = s.member_id')
//            ->where("a.from_me_sex = 2 and a.to_me_sex = 1 and s.me_qd != '' and s.me_add_time >= $start_time and s.me_add_time <= $end_time and a.timestamp >= $start_time_hm and a.timestamp <= $end_time_hm")
//            ->field("a.fromUserId,f.me_nick_name, COUNT(DISTINCT toUserId) as data_count")  // 选择字段：fromUserId 和统计数量（toUserId 去重）
//            ->group('fromUserId')  // 按 fromUserId 分组
//            ->order('data_count DESC')  // 按 data_count 从大到小排序
//            ->select();
//        return json($data);

        $data = Db::table('fa_rong_msg')
            ->alias('a')
            ->join('fa_member f', 'a.fromUserId = f.member_id')  // 关联发送者表
            ->join('fa_member s', 'a.toUserId = s.member_id')    // 关联接收者表
            ->where('a.from_me_sex', 2)                          // 发送者性别为女
            ->where('a.to_me_sex', 1)                            // 接收者性别为男
            ->where('s.me_qd', '<>', '')                         // 接收者的 me_qd 不为空
            ->where($whehe)
            ->whereBetween('s.me_add_time', [$start_time, $end_time]) // 接收者注册时间范围
            ->whereBetween('a.timestamp', [$start_time_hm, $end_time_hm]) // 消息时间戳范围
            ->whereExists(function ($query) {                    // 子查询：筛选发送者与接收者消息数量 > 4
                $query->table('fa_rong_msg')
                    ->alias('b')
                    ->whereColumn('b.fromUserId', 'a.fromUserId') // 同一发送者
                    ->whereColumn('b.toUserId', 'a.toUserId')     // 同一接收者
                    ->group('b.fromUserId, b.toUserId')
                    ->having('COUNT(*) > 0');                    // 消息数量 > 4
            })
            ->field('a.fromUserId,f.me_uid,f.me_phone,f.me_nick_name, COUNT(DISTINCT a.toUserId) as data_count') // 选择字段
            ->group('a.fromUserId')                              // 按发送者分组
            ->order('data_count DESC,a.id desc')                           // 按统计数量排序
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);

        $adminid = $this->uid;
        $data->each(function ($v, $k)use($adminid){
            //只有超管能看全部手机号
            if($adminid != 1){
                $v['me_phone'] = hide_phone_number($v['me_phone']);
            }
            if(!empty(strpos($v['me_phone'], 'zx'))){
                $v['me_phone'] = explode('zx',$v['me_phone'])[0].'（已注销）';
                $v['me_nick_name'] = explode('zx',$v['me_nick_name'])[0].'（已注销）';
            }
            return $v;
        });
        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
            'day' => date('Y-m-d',$start_time),
        ]);
        return $this->fetch();
    }


    /**
     * 查询聊天人数详情
     * User:@hang
     */
    public function getboylist(Request $request)
    {
        $id = input('id');
        $arr = explode('#',$id);
        $fromUserId = $arr[0];
        $start_time = strtotime($arr[1].' 00:00:00');//开始秒
        $end_time = strtotime($arr[1].' 23:59:59');//结束秒
        $start_time_hm = bcmul($start_time,1000,0);//开始毫秒
        $end_time_hm = bcmul($end_time,1000,0);//结束毫秒

        $param = $request->param();
        $whehe = array();
        if (isset($param['member_id']) && !empty($param['member_id'])) {
            $whehe[] = ['s.member_id','=',$param['member_id']];
        }
        if (isset($param['me_uid']) && !empty($param['me_uid'])) {
            $whehe[] = ['s.me_uid','like',"%{$param['me_uid']}%"];
        }

        $data = Db::table('fa_rong_msg')
            ->alias('a')
            ->join('fa_member f', 'a.fromUserId = f.member_id')  // 关联发送者表
            ->join('fa_member s', 'a.toUserId = s.member_id')    // 关联接收者表
            ->where('a.fromUserId', $fromUserId)                        // 发送者ID为114
            ->where('a.to_me_sex', 1)                           // 接收者性别为男
            ->where('s.me_qd', '<>', '')                        // 接收者的 me_qd 不为空
            ->where($whehe)
            ->whereBetween('s.me_add_time', [$start_time, $end_time]) // 接收者注册时间范围
            ->whereBetween('a.timestamp', [$start_time_hm, $end_time_hm]) // 消息时间戳范围
            ->whereExists(function ($query) {                   // 子查询：筛选发送者与接收者消息数量 > 4
                $query->table('fa_rong_msg')
                    ->alias('b')
                    ->whereColumn('b.fromUserId', 'a.fromUserId') // 同一发送者
                    ->whereColumn('b.toUserId', 'a.toUserId')     // 同一接收者
                    ->group('b.fromUserId, b.toUserId')
                    ->having('COUNT(*) > 0');                    // 消息数量 > 4
            })
            ->field('a.fromUserId,f.me_uid,f.me_phone,f.me_nick_name,a.toUserId,s.me_uid as s_me_uid,s.me_phone as s_me_phone,s.me_nick_name as s_me_nick_name,s.me_qd,s.me_add_time, COUNT(*) as chat_count') // 选择字段：接收者ID、昵称、聊天次数
            ->group('a.toUserId')                               // 按接收者分组
            ->order('chat_count DESC')                          // 按聊天次数从大到小排序
            ->paginate($this->admin['per_page'],false,['query'=>request()->param()]);
//        echo count($data);
//        return json($data);

        $adminid = $this->uid;
        $data->each(function ($v, $k)use($adminid) {
            //只有超管能看全部手机号
            if($adminid != 1){
                $v['s_me_phone'] = hide_phone_number($v['s_me_phone']);
            }
            if(!empty(strpos($v['me_phone'], 'zx'))){
                $v['me_phone'] = explode('zx',$v['me_phone'])[0].'（已注销）';
                $v['me_nick_name'] = explode('zx',$v['me_nick_name'])[0].'（已注销）';
            }
            if(!empty(strpos($v['s_me_phone'], 'zx'))){
                $v['s_me_phone'] = explode('zx',$v['s_me_phone'])[0].'（已注销）';
                $v['s_me_nick_name'] = explode('zx',$v['s_me_nick_name'])[0].'（已注销）';
            }
            $v['me_add_time'] = date('Y-m-d H:i:s',$v['me_add_time']);
            return $v;
        });

        //关键词，排序等赋值
        $this->assign($request->get());
        $this->assign([
            'data'  => $data,
            'page'  => $data->render(),
            'total' => $data->total(),
            'id' => $id,
            'day' => date('Y-m-d',$start_time),
        ]);
        return $this->fetch();
    }





}
